package model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class GarantiaDAO {
	public void incluir(Garantia garantia) throws SQLException {
		Statement comando = DBConnection.getInstancia().conn.createStatement();
		String query = "INSERT INTO garantia(contrato,id_bem) VALUES(";
		query += Integer.toString(garantia.getContrato().getNumero());
		query += "," + garantia.getBem().getId() + ")";
		comando.executeUpdate(query);
	}

	public void alterar(Garantia garantia) throws SQLException {
		Statement comando = DBConnection.getInstancia().conn.createStatement();
		String query = "UPDATE garantia ";
		query += "SET clausula = '" + garantia.getClausula() + "',";
		query += "valor = " + Float.toString(garantia.getValor()) + " ";
		query += "WHERE contrato = " + Integer.toString(garantia.getContrato().getNumero());
		query += " AND id_bem = " + Integer.toString(garantia.getBem().getId());
		comando.executeUpdate(query);
	}

	public void excluir(int numero,String[] ids) throws SQLException {
		Statement comando = DBConnection.getInstancia().conn.createStatement();
		// Preparar lista
		String lista = "'0'";
		for (int i=0;i<ids.length;i++)
			lista += ","+ids[i];
		// Executar operacao
		String query = "DELETE FROM garantia ";
		query += "WHERE contrato = " + Integer.toString(numero);
		query += " AND id_bem NOT IN (" + lista + ")";
		comando.executeUpdate(query);
	}

	public ArrayList<Garantia> consultar(Garantia garantia)
			throws SQLException {
		Statement comando = DBConnection.getInstancia().conn.createStatement();
		ArrayList<Garantia> retorno = new ArrayList<Garantia>();
		ResultSet rs;
		try {
			String query = "SELECT * FROM garantia WHERE 1=1";
			if (!(null == garantia.getContrato()))
				query += " AND contrato = " + Integer.toString(garantia.getContrato().getNumero());
			if (!(null == garantia.getBem()))
				query += " AND id_bem = " + garantia.getBem().getId();
			rs = comando.executeQuery(query);
			while (rs.next()) {
				Garantia g = new Garantia();
				g.setContrato(new Contrato(rs.getInt("contrato")));
				g.setBem(new Bem(rs.getInt("id_bem")));
				g.setClausula(rs.getString("clausula"));
				g.setValor(rs.getFloat("valor"));
				retorno.add(g);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return retorno;
	}
}